<?php

namespace App\Models\CacheModel\zl2;

use App\Tools\Astrolog\DailyFortune;
use App\Tools\Util;
use Illuminate\Database\Eloquent\Model;
use Log;
use AstroTool\Cache\CacheManage;

class Zl2AstrFortuneContent extends Model
{
    protected $table = 'zl2_astr_fortune_content';

    protected $cacheModel = 'astro_fortune.astro_fortune_change_content';

    public function SaveData(array $data, array $recodeInfo)
    {
        try
        {
            // 写入数据
            $id = $this->insertGetId($data);

            $cacheKey = "{$data['uid']}:{$data['rid']}:{$data['date']}:{$data['data_type']}";
            CacheManage::getInstance()->setCacheConfig($this->cacheModel, $cacheKey)->rmCache('details');
            // 解锁列表添加
            CacheManage::getInstance()->setCacheConfig($this->cacheModel)->setCacheKeyDetail('unlock_date', "{$data['uid']}:{$data['rid']}:{$data['data_type']}")
                ->setListCacheTime(259200)->listAdd([$data['date'] => $data['date']], 0, 'unlock_date');
            // 发送计算队列
            Util::queuePush('astro_fortune_change_calculate', ['id' => $id, 'recode_info' => $recodeInfo], 0);
            return true;
        }
        catch (\Exception $e)
        {
            Log::write('Zl2AstrFortuneContent model => SaveData()异常：' . $e->getMessage() . '失败行数：' . $e->getLine(), 'error');
            return false;
        }
    }

    /**
     * 获取计算的 日期
     * @param int $uid
     * @param int $rid
     * @param int $dataType 1=>首页｜纯净       2=>进行中
     * @return int[]|string[]
     * @throws \Exception
     */
    public function getUnlockDateData(int $uid, int $rid, int $dataType = 1)
    {
        $unlockData = CacheManage::getInstance()
            ->setCacheConfig($this->cacheModel)
            ->setCacheKeyDetail('unlock_date', $uid . ':' . $rid . ':' . $dataType)
            ->setListCacheTime(259200)  // 3天过期时间
            ->setPage(-1)
            ->getListPageDataIds(function ($isCache = true, $sortType = 'desc') use ($uid, $rid, $dataType)
            {
                try
                {
                    $unlockDate = $this->where(['uid' => $uid, 'rid' => $rid, 'data_type' => $dataType])->column('date');
                    $resData = [];
                    foreach ($unlockDate as $date)
                    {
                        $resData[$date] = ['date' => $date];
                    }
                    return $resData;
                }
                catch (\Exception $e)
                {
                    return [];
                }
            }, 'date', 0, 'unlock_date');

        $dates = array_keys($unlockData['data']);

        $resData = [];
        foreach ($dates as $dateItem)
        {
            $resData[] = date('Y-m-d', strtotime($dateItem));
        }

        return $resData;
    }


    /**
     * 获取 星运变动 信息
     * @param int $uid
     * @param array $recodeInfo 档案信息
     * @param int $time
     * @param int $type 1=>首页｜纯净   2=>进行中
     * @return array
     * @throws \Exception
     */
    public function getUserAstroFortuneChangeData(int $uid, array $recodeInfo, int $time, int $type)
    {
        $date = (int)date('Ymd', $time);
        $recodeHashKey = Util::getRecodeHashKey($recodeInfo);
        $cacheKey = $uid . ':' . $recodeInfo['id'] . ':' . date('Ymd', $time) . ':' . $type;
        $data = CacheManage::getInstance()->setCacheConfig($this->cacheModel, $cacheKey)
            ->getDataAndSet(function () use ($uid, $recodeInfo, $date, $type)
            {
                try
                {
                    $data = $this->where([['uid', '=', $uid],['rid', '=', $recodeInfo['id']],['data_type', '=', $type],['date', '=', $date],])->get(['id', 'hash', 'status', 'content', 'create_time'])->keyBy('hash')->toArray();

                    $resData = [];
                    foreach ($data as $hash => $dataItem)
                    {
                        $dataItem['id'] = (int)$dataItem['id'];
                        $dataItem['status'] = (int)$dataItem['status'];
                        $dataItem['content'] = $dataItem['content'] ? json_decode($dataItem['content'], true) : [];
                        $resData[$hash] = json_encode($dataItem, JSON_UNESCAPED_UNICODE);
                    }

                    return $resData;
                }
                catch (\Exception $e)
                {
                    Log::write('Zl2AstrFortuneContent model => getUserAstroFortuneChangeData()异常：' . $e->getMessage() . '失败行数：' . $e->getLine(), 'error');
                    return [];
                }
            });

        $resData = [];
        if (isset($data[$recodeHashKey]))
        {
            $resData = json_decode($data[$recodeHashKey], true);
            $resData['recode_is_change'] = false;
        } else
        {
            foreach ($data as $datum)
            {
                $datum1 = json_decode($datum, true);
                if (empty($resData))
                {
                    $resData = $datum1;
                } else
                {
                    if ($datum1['id'] > $resData['id'])
                    {
                        $resData = $datum1;
                    }
                }
                $resData['recode_is_change'] = true;
            }
        }

        return $resData;
    }


}
